package org.jeecg.modules.third.nucarf;

import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.middleware.rabbitmq.gas.GasMqUtil;
import org.jeecg.modules.third.hgfuelenergy.HgFuelEnergyService;
import org.jeecg.modules.third.nucarf.dto.BaseResult;
import org.jeecg.modules.third.nucarf.dto.CUInfo;
import org.jeecg.modules.third.nucarf.dto.NucartResult;
import org.jeecg.modules.wlhy.gas.entity.HyShippingNoteGas;
import org.jeecg.modules.wlhy.gas.service.IHyShippingNoteGasService;
import org.jeecg.modules.wlhy.hyconfig.entity.HyConfig;
import org.jeecg.modules.wlhy.hydriver.entity.HyDriver;
import org.jeecg.modules.wlhy.hydriver.service.IHyDriverService;
import org.jeecg.modules.wlhy.hyvehicle.entity.HyVehicle;
import org.jeecg.modules.wlhy.hyvehicle.service.IHyVehicleService;
import org.jeecg.modules.wlhy.shipping.entity.HyShippingNote;
import org.jeecg.modules.wlhy.shipping.service.IHyShippingNoteService;
import org.jeecg.modules.wlhy.utils.HyConfigUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;

@Service
public class GasService {

    @Autowired
    private NucartUtils nucartUtils;

    @Autowired
    private HgFuelEnergyService hgFuelEnergyService;

    @Autowired
    private IHyShippingNoteService hyShippingNoteService;

    @Autowired
    private IHyDriverService hyDriverService;

    @Autowired
    private IHyVehicleService hyVehicleService;

    @Autowired
    private IHyShippingNoteGasService hyShippingNoteGasService;

    public Result<?> getGasAccInfo() {
        HyConfig gasConfig = this.checkConfig();
        String nucarfAppid = gasConfig.getGasAppid();
        String nucarfSecret = gasConfig.getGasSecret();
        NucartResult<BaseResult> r = (NucartResult<BaseResult>) nucartUtils.getCompanyMoney(nucarfAppid, nucarfSecret);
        if(r.isSuccess()){
            return  Result.OK(r.getResult());
        }else{
            return Result.error(r.getMessage());
        }
    }

    /**
     * 油气平台
     * @return
     */
    public Result<?> getHgGasAccInfo() {
        HyConfig gasConfig = this.checkHgConfig();
        String hgGasAppid = gasConfig.getHgGasAppid() ;
        String hgGasSecret = gasConfig.getHgGasSecret() ;
        Result<?> r = hgFuelEnergyService.getCompanyMoney(hgGasAppid, hgGasSecret);
        if(r.isSuccess()){
            return  Result.OK(r.getResult());
        }else{
            return Result.error(r.getMessage());
        }
    }

    public void rechargeMsg(HyShippingNoteGas gas) {
        try {
            if("1".equals(gas.getIzUsedGas())){
               this.checkConfig();
            }
            if("3".equals(gas.getIzUsedGas())){
               this.checkHgConfig();
            }
            GasMqUtil.recharge(gas.getId());
        }catch (Exception e){
            gas.setGasStatus("9");
            gas.setGasRemark(e.getMessage());
            hyShippingNoteGasService.updateById(gas);
        }
    }

    @Transactional
    public void handleRecharge(String id) {
        HyShippingNoteGas gas = null;

        try {
            gas = hyShippingNoteGasService.getByIdForUpdate(id);
            if (gas == null) {
                return;
            }
            if(!"1".equals(gas.getGasStatus())){
                return;
            }
            HyShippingNote shippingNote = hyShippingNoteService.getById(gas.getShippingId());
            if (shippingNote == null) {
                throw new JeecgBootException("运单信息不存在");
            }
            String izUsedGas = shippingNote.getIzUsedGas();
            if (!"1".equals(izUsedGas) && !"3".equals(izUsedGas) ) {
                throw new JeecgBootException("运单信息错误");
            }

            HyVehicle vehicle = hyVehicleService.getById(shippingNote.getVehicleId());
            if (vehicle == null) {
                throw new JeecgBootException("车辆信息不存在");
            }

            HyDriver driver = hyDriverService.getById(gas.getDriverId());
            if (driver == null) {
                throw new JeecgBootException("司机信息不存在!");
            }

            String vehicleNumber = gas.getVehicleNumber();
            String driverName = gas.getDriverName();
            String idcard = driver.getIdcard();
            String telephone = driver.getTelephone();
            String sendAddress = shippingNote.getSendAddress();
            String receiveAddress = shippingNote.getReceiveAddress();
            String remark = "油气费,运单号:" + shippingNote.getShippingNoteNumber();

            if("1".equals(gas.getIzUsedGas())){
                HyConfig gasConfig =  this.checkConfig() ;
                String nucarfAppid = gasConfig.getGasAppid();
                String nucarfSecret = gasConfig.getGasSecret();

                BigDecimal gasRechargeAmount = gas.getGasRechargeAmount().multiply(new BigDecimal("100"));
                String money = gasRechargeAmount.toString();

                //充值
                NucartResult<CUInfo> r = (NucartResult<CUInfo>) nucartUtils.createUser(
                        driverName, telephone, idcard, vehicleNumber, money, nucarfAppid,
                        nucarfSecret, sendAddress, receiveAddress, remark, shippingNote.getShippingNoteNumber(),
                        vehicle.getVehicleEnergyType()

                );
                if (r.isSuccess()) {
                    BigDecimal gasAmount = gasRechargeAmount.divide(new BigDecimal("100"));
                    String flowNum = StringUtils.isNotBlank(r.getResult().getFlowNumber()) ? r.getResult().getFlowNumber() : StringUtils.EMPTY;
                    gas.setGasStatus("2");
                    gas.setGasAmount(gasAmount);
                    gas.setGasFlowNumber(flowNum);
                    gas.setRechargeTime(new Date());
                    hyShippingNoteGasService.updateById(gas);
                    return;
                }else {
                    gas.setGasRemark(r.getMessage());
                }
            }
            if("3".equals(gas.getIzUsedGas())){
                HyConfig gasConfig =  this.checkHgConfig() ;
                String hgGasAppid = gasConfig.getHgGasAppid() ;
                String hgGasSecret = gasConfig.getHgGasSecret() ;

                BigDecimal gasRechargeAmount = gas.getGasRechargeAmount();
                String money = String.format("%.2f", gasRechargeAmount);
                Result createUserResult  = hgFuelEnergyService
                        .createUser( driverName, telephone, idcard, vehicleNumber, hgGasAppid, hgGasSecret);
                if(!createUserResult.isSuccess()){
                    gas.setGasRemark(createUserResult.getMessage());
                }else {
                    //充值
                    Result rechargeResult =  hgFuelEnergyService.userRecharge(
                            driverName, telephone, idcard, vehicleNumber, money, hgGasAppid,
                            hgGasSecret, sendAddress, receiveAddress, remark, shippingNote.getShippingNoteNumber(),
                            vehicle.getVehicleEnergyType()
                    );
                    if (rechargeResult.isSuccess()) {
                        gas.setGasStatus("2");
                        gas.setGasAmount(gasRechargeAmount );
                        gas.setGasFlowNumber("");
                        gas.setRechargeTime(new Date());
                        hyShippingNoteGasService.updateById(gas);
                        return;
                    }else {
                        gas.setGasRemark(rechargeResult.getMessage());
                    }
                }

            }

        }catch (Exception e) {
            if (gas != null) {
                gas.setGasRemark(e.getMessage());
            }
        }
        if (gas != null) {
            gas.setGasStatus("9");
            hyShippingNoteGasService.updateById(gas);
        }
    }

    /**
     * 充值失败重新充值
     * @param id
     * @return
     */
    @Transactional
    public Result<?> rechargeFail(String id) {
        HyShippingNoteGas gas = hyShippingNoteGasService.getByIdForUpdate(id);
        if(gas == null){
            return Result.error("数据不存在!");
        }
        if(!"9".equals(gas.getGasStatus())){
            return Result.error("不能充值!");
        }

        HyShippingNote shippingNote = hyShippingNoteService.getById(gas.getShippingId());
        if(shippingNote == null){
            return Result.error("运单信息不存在");
        }

        HyVehicle hyVehicle = hyVehicleService.getById(shippingNote.getVehicleId());
        if(hyVehicle == null){
            return Result.error("车辆信息不存在");
        }
        HyDriver driver = hyDriverService.getById(gas.getDriverId());
        if (driver == null) {
            return Result.error("司机信息不存在!");
        }

        String vehicleNumber = gas.getVehicleNumber();
        String driverName = gas.getDriverName();
        String idcard = driver.getIdcard();
        String telephone = driver.getTelephone();
        //充值
        String sendAddress = shippingNote.getSendAddress();
        String receiveAddress = shippingNote.getReceiveAddress();
        String remark = "油气费,运单号:" + shippingNote.getShippingNoteNumber();
        if("1".equals(gas.getIzUsedGas())){
            HyConfig gasConfig =  this.checkConfig();
            String nucarfAppid = gasConfig.getGasAppid();
            String nucarfSecret = gasConfig.getGasSecret();

            BigDecimal gasRechargeAmount = gas.getGasRechargeAmount().multiply(new BigDecimal("100"));
            String money = gasRechargeAmount.toString();
            NucartResult<CUInfo> r = (NucartResult<CUInfo>) nucartUtils.createUser(
                    driverName, telephone, idcard, vehicleNumber, money, nucarfAppid,
                    nucarfSecret,sendAddress,receiveAddress,remark,shippingNote.getShippingNoteNumber(),
                    hyVehicle.getVehicleEnergyType()

            );
            if(r.isSuccess()){
                BigDecimal gasAmount = gasRechargeAmount.divide(new BigDecimal("100"));
                String flowNum = StringUtils.isNotBlank(r.getResult().getFlowNumber()) ?  r.getResult().getFlowNumber() : StringUtils.EMPTY;
                gas.setGasStatus("2");
                gas.setGasAmount(gasAmount);
                gas.setGasFlowNumber(flowNum);
                gas.setRechargeTime(new Date());
                hyShippingNoteGasService.updateById(gas);
                return Result.OK("充值成功!");
            }else{
                gas.setGasStatus("9");
                gas.setGasRemark(r.getMessage());
                hyShippingNoteGasService.updateById(gas);
                return Result.error("充值失败！" + r.getMessage());
            }
        }

        if("3".equals(gas.getIzUsedGas())){

            HyConfig gasConfig =  this.checkHgConfig() ;
            String hgGasAppid = gasConfig.getHgGasAppid() ;
            String hgGasSecret = gasConfig.getHgGasSecret() ;

            BigDecimal gasRechargeAmount = gas.getGasRechargeAmount();
            String money =  gasRechargeAmount.toString();
            Result createUserResult  = hgFuelEnergyService
                    .createUser( driverName, telephone, idcard, vehicleNumber, hgGasAppid, hgGasSecret);
            if(!createUserResult.isSuccess()){
                return Result.error("充值失败！" + createUserResult.getMessage());
            }else {
                //充值
                Result r =  hgFuelEnergyService.userRecharge(
                        driverName, telephone, idcard, vehicleNumber, money, hgGasAppid,
                        hgGasSecret, sendAddress, receiveAddress, remark, shippingNote.getShippingNoteNumber(),
                        hyVehicle.getVehicleEnergyType()
                );
                if (r.isSuccess()) {
                    gas.setGasStatus("2");
                    gas.setGasAmount(gasRechargeAmount );
                    gas.setGasFlowNumber("");
                    gas.setRechargeTime(new Date());
                    hyShippingNoteGasService.updateById(gas);
                    return Result.OK("充值成功!");
                }else {
                    gas.setGasStatus("9");
                    gas.setGasRemark(r.getMessage());
                    hyShippingNoteGasService.updateById(gas);
                    return Result.error("充值失败！" + r.getMessage());
                }
            }
        }
      return Result.OK("充值失败!");
    }

    /**
     * 回收重新充值
     * @param id
     * @param money
     * @param vehicleEnergyType
     * @return
     */
    @Transactional
    public Result<?> rechargeBack(String id ,String money  ,String vehicleEnergyType) {
        HyShippingNoteGas gas = hyShippingNoteGasService.getByIdForUpdate(id);
        if(gas == null){
            return Result.error("数据不存在!");
        }

        if(!"4".equals(gas.getGasStatus())){
            return Result.error("不能充值!");
        }
        if(StringUtils.isBlank(money)){
            return Result.error("充值金额不能为空!");
        }

        BigDecimal moneyBigDecimal = new BigDecimal(money);
        if(moneyBigDecimal.compareTo(BigDecimal.ZERO) == 0){
            return Result.error("充值金额不能为空!");
        }
//        if(moneyBigDecimal.compareTo(gas.getGasAmount()) == 1 ){
//            return Result.error("充值金额不能大于运单充值金额!");
//        }
        if(StringUtils.isBlank(vehicleEnergyType)){
            return Result.error("车辆能源类型不为空!");
        }
        String as = "E,B";
        int result1 = as.indexOf(vehicleEnergyType);
        if (result1 == -1) {
            return Result.error("车辆能源类型不正确! 车辆能源类型为天然气、柴油");
        }
        HyShippingNote shippingNote = hyShippingNoteService.getByIdForUpdate(gas.getShippingId());
        if(shippingNote == null){
            return Result.error("运单信息不存在");
        }

        if(moneyBigDecimal.compareTo(shippingNote.getGasRechargeAmount()) != 0) {
            String shippingPayStatus = shippingNote.getShippingPayStatus();
            if(!"0".equals(shippingPayStatus) &&
                    !"1".equals(shippingPayStatus) &&
                    !"8".equals(shippingPayStatus)) {
                return Result.error("运单已经对账完成或者支付完成充值金额不能修改!");
            }
        }

        HyVehicle hyVehicle = hyVehicleService.getById(shippingNote.getVehicleId());
        if(hyVehicle == null){
            return Result.error("车辆信息不存在");
        }
        HyDriver driver = hyDriverService.getById(gas.getDriverId());
        if (driver == null) {
            return Result.error("司机信息不存在!");
        }

        String vehicleNumber = gas.getVehicleNumber();
        String driverName = gas.getDriverName();
        String idcard = driver.getIdcard();
        String telephone = driver.getTelephone();
        //充值
        String sendAddress = shippingNote.getSendAddress();
        String receiveAddress = shippingNote.getReceiveAddress();
        String remark = "油气费,运单号:" + shippingNote.getShippingNoteNumber();
        if("1".equals(gas.getIzUsedGas())){
            HyConfig gasConfig =  this.checkConfig();
            String nucarfAppid = gasConfig.getGasAppid();
            String nucarfSecret = gasConfig.getGasSecret();

            BigDecimal gasRechargeAmount = moneyBigDecimal.multiply(new BigDecimal("100"));
            String moneyString = gasRechargeAmount.toString();
            NucartResult<CUInfo> r = (NucartResult<CUInfo>) nucartUtils.createUser(
                                        driverName, telephone, idcard, vehicleNumber, moneyString, nucarfAppid,
                                        nucarfSecret,sendAddress,receiveAddress,remark,shippingNote.getShippingNoteNumber(),
                                        vehicleEnergyType
                                );
            if(r.isSuccess()){
                BigDecimal gasAmount = gasRechargeAmount.divide(new BigDecimal("100"));
                String flowNum = StringUtils.isNotBlank(r.getResult().getFlowNumber()) ?  r.getResult().getFlowNumber() : StringUtils.EMPTY;
                gas.setGasStatus("2");
                gas.setGasAmount(gasAmount);
                gas.setGasRechargeAmount(gasAmount);
                gas.setGasFlowNumber(flowNum);
                gas.setRechargeTime(new Date());
                gas.setVehicleEnergyType(vehicleEnergyType);
                hyShippingNoteGasService.updateById(gas);
                //修改充值金额需要修改运单充值金额
                if(moneyBigDecimal.compareTo(shippingNote.getGasRechargeAmount()) != 0){
                    shippingNote.setGasRechargeAmount(moneyBigDecimal);
                    hyShippingNoteService.updateById(shippingNote);
                }
                //能源类型变动需要修改车辆能源类型
                if(!vehicleEnergyType.equals(hyVehicle.getVehicleEnergyType())){
                    hyVehicle.setVehicleEnergyType(vehicleEnergyType) ;
                    hyVehicleService.updateById(hyVehicle);
                }
                return Result.OK("充值成功!");
            }else{
                gas.setGasStatus("9");
                gas.setGasRemark(r.getMessage());
                hyShippingNoteGasService.updateById(gas);
                return Result.error("充值失败！" + r.getMessage());
            }
        }

        if("3".equals(gas.getIzUsedGas())){

            HyConfig gasConfig =  this.checkHgConfig() ;
            String hgGasAppid = gasConfig.getHgGasAppid() ;
            String hgGasSecret = gasConfig.getHgGasSecret() ;
            //充值
            Result r =  hgFuelEnergyService.userRecharge(
                                driverName, telephone, idcard, vehicleNumber, money, hgGasAppid,
                                hgGasSecret, sendAddress, receiveAddress, remark, shippingNote.getShippingNoteNumber(),
                                vehicleEnergyType
                        );
            if (r.isSuccess()) {
                gas.setGasStatus("2");
                gas.setGasAmount(moneyBigDecimal );
                gas.setGasRechargeAmount(moneyBigDecimal);
                gas.setGasFlowNumber("");
                gas.setRechargeTime(new Date());
                gas.setVehicleEnergyType(vehicleEnergyType);
                hyShippingNoteGasService.updateById(gas);
                //修改充值金额需要修改运单充值金额
                if(moneyBigDecimal.compareTo(shippingNote.getGasRechargeAmount()) != 0){
                    shippingNote.setGasRechargeAmount(moneyBigDecimal);
                    hyShippingNoteService.updateById(shippingNote);
                }
                //能源类型变动需要修改车辆能源类型
                if(!vehicleEnergyType.equals(hyVehicle.getVehicleEnergyType())){
                    hyVehicle.setVehicleEnergyType(vehicleEnergyType);
                    hyVehicleService.updateById(hyVehicle);
                }
                return Result.OK("充值成功!");
            }else {
                gas.setGasStatus("9");
                gas.setGasRemark(r.getMessage());
                hyShippingNoteGasService.updateById(gas);
                return Result.error("充值失败！" + r.getMessage());
            }

        }
        return Result.OK("充值失败!");
    }



    @Transactional
    public void backMsg(HyShippingNote hyShippingNote) {
        HyShippingNoteGas gas = hyShippingNoteGasService.getByShippingIdForUpdate(hyShippingNote.getId());
        if(gas == null){
            return;
        }
        String gasStatus = gas.getGasStatus();
        //充值成功时，回收油气
        if ("2".equals(gasStatus)) {
            gas.setGasStatus("3");//待回收
            hyShippingNoteGasService.updateById(gas);
            try {
                if("1".equals(gas.getIzUsedGas())){
                    this.checkConfig();
                }
                if("3".equals(gas.getIzUsedGas())){
                    this.checkHgConfig();
                }
                GasMqUtil.back(gas.getId());
            }catch (Exception e){
                gas.setGasStatus("5");
                gas.setGasRemark(e.getMessage());
                hyShippingNoteGasService.updateById(gas);
            }
        }
    }

    @Transactional
    public void handleBack(String id) {
        HyShippingNoteGas gas = null;
        try {
            gas = hyShippingNoteGasService.getByIdForUpdate(id);
            if (gas == null) {
                return ;
            }
            if (!"5".equals(gas.getGasStatus()) && !"3".equals(gas.getGasStatus())) {
                return;
            }

            HyShippingNote shippingNote = hyShippingNoteService.getById(gas.getShippingId());
            if (shippingNote == null) {
                throw new JeecgBootException("运单数据不存在!");
            }
            HyDriver driver = hyDriverService.getById(gas.getDriverId());
            if (driver == null) {
                throw new JeecgBootException("司机信息不存在!");
            }

            HyVehicle hyVehicle = hyVehicleService.getById(shippingNote.getVehicleId());
            if (hyVehicle == null) {
                throw new JeecgBootException("车辆信息不存在");
            }

            if("1".equals(gas.getIzUsedGas())){
                HyConfig gasConfig = this.checkConfig();
                String nucarfAppid = gasConfig.getGasAppid();
                String nucarfSecret = gasConfig.getGasSecret();
                //回收
                BigDecimal gasAmount1 = gas.getGasAmount().multiply(new BigDecimal("100"));
                String driverName = driver.getTelephone();
                NucartResult<?> r = nucartUtils.backMoney(
                        driverName, gasAmount1.toString(), nucarfAppid, nucarfSecret, hyVehicle.getVehicleEnergyType()
                );
                if (r.isSuccess()) {
                    gas.setGasStatus("4");//已回收
                    hyShippingNoteGasService.updateById(gas);
                    return ;
                } else {
                    gas.setGasRemark(r.getMessage());
                }
            }
            if("3".equals(gas.getIzUsedGas())){

                HyConfig gasConfig = this.checkHgConfig();
                String hgGasAppid = gasConfig.getHgGasAppid() ;
                String hgGasSecret = gasConfig.getHgGasSecret() ;
                //回收
                BigDecimal gasAmount = gas.getGasAmount();
                String money = String.format("%.2f", gasAmount);
                String driverName = gas.getDriverName();
                String telephone =  driver.getTelephone();
                Result<?> r = hgFuelEnergyService.backMoney(
                        driverName,telephone, money, hgGasAppid, hgGasSecret, hyVehicle.getVehicleEnergyType()
                );
                if (r.isSuccess()) {
                    gas.setGasStatus("4");//已回收
                    hyShippingNoteGasService.updateById(gas);
                    return ;
                } else {
                    gas.setGasRemark(r.getMessage());
                }
            }


        }catch (Exception e){
            if(gas!=null) {
                gas.setGasRemark(e.getMessage());
            }
        }
        if(gas != null) {
            gas.setGasStatus("5");
            hyShippingNoteGasService.updateById(gas);
        }
    }

    @Transactional
    public Result<?> back(String id) {
        HyShippingNoteGas gas = hyShippingNoteGasService.getByIdForUpdate(id);
        if(gas == null){
            return Result.error("数据不存在!");
        }
        //油气状态(1待充值2已充值 3待回收 4已回收 5 回收失败 9充值失败)
        if(!"5".equals(gas.getGasStatus()) && !"3".equals(gas.getGasStatus()) && !"2".equals(gas.getGasStatus())){
            return Result.error("不能回收!");
        }

        HyShippingNote shippingNote = hyShippingNoteService.getById(gas.getShippingId());
        if(shippingNote == null){
            return Result.error("运单数据不存在!");
        }

        HyVehicle hyVehicle = hyVehicleService.getById(shippingNote.getVehicleId());
        if(hyVehicle == null){
            return Result.error("车辆信息不存在");
        }
        HyDriver driver = hyDriverService.getById(gas.getDriverId());
        if (driver == null) {
            return Result.error("司机信息不存在!");
        }
        if("1".equals(gas.getIzUsedGas())){
            HyConfig gasConfig = this.checkConfig();
            String nucarfAppid = gasConfig.getGasAppid();
            String nucarfSecret = gasConfig.getGasSecret();
            //已回收
            BigDecimal gasAmount1 = gas.getGasAmount().multiply(new BigDecimal("100"));
            String driverName = driver.getTelephone();
            //万金油回收查询余额
            this.checkNucarfBackMoney(nucarfAppid, nucarfSecret, gasAmount1, driverName);

            NucartResult<?> r = nucartUtils.backMoney(
                    driverName, gasAmount1.toString(), nucarfAppid, nucarfSecret,hyVehicle.getVehicleEnergyType()
            );
            if(r.isSuccess()){
                gas.setGasStatus("4");//已回收
                hyShippingNoteGasService.updateById(gas);
                return Result.OK("回收成功!");
            }else {
                gas.setGasStatus("5");
                gas.setGasRemark(r.getMessage());
                hyShippingNoteGasService.updateById(gas);
                return Result.error("回收失败！" + r.getMessage());
            }
        }
        if("3".equals(gas.getIzUsedGas())){
            HyConfig gasConfig = this.checkHgConfig();
            String hgGasAppid = gasConfig.getHgGasAppid() ;
            String hgGasSecret = gasConfig.getHgGasSecret() ;
            //回收
            BigDecimal gasAmount = gas.getGasAmount();
            String money = String.format("%.2f", gasAmount);
            String driverName = gas.getDriverName();
            String telephone =  driver.getTelephone();
            //油气平台回收查询余额
            this.checkBackMoney(hgGasAppid, hgGasSecret, gasAmount, driverName, telephone);

            Result<?> r = hgFuelEnergyService.backMoney(
                    driverName,telephone, money, hgGasAppid, hgGasSecret, hyVehicle.getVehicleEnergyType()
            );
            if(r.isSuccess()){
                gas.setGasStatus("4");//已回收
                hyShippingNoteGasService.updateById(gas);
                return Result.OK("回收成功!");
            }else {
                gas.setGasStatus("5");
                gas.setGasRemark(r.getMessage());
                hyShippingNoteGasService.updateById(gas);
                return Result.error("回收失败！" + r.getMessage());
            }
        }

        return Result.OK("回收失败!");
    }

    /**
     * 油气平台回收查询余额
     * @param hgGasAppid
     * @param hgGasSecret
     * @param gasAmount
     * @param driverName
     * @param telephone
     */
    private void checkBackMoney(String hgGasAppid, String hgGasSecret, BigDecimal gasAmount, String driverName, String telephone) {
        Result<?> hgResult =  hgFuelEnergyService.getBackMoney(driverName, telephone, hgGasAppid, hgGasSecret);

        if(!hgResult.isSuccess()) {
            throw new JeecgBootException("查询司机余额失败请重新查询!");
        }else{
            String balance = hgResult.getResult() != null ?  hgResult.getResult().toString() : StringUtils.EMPTY;
            if(StringUtils.isBlank(balance)){
                throw new JeecgBootException("司机余额不足不能回收!");
            }
            BigDecimal  balanceBig = new BigDecimal(balance);
            if(gasAmount.compareTo(balanceBig) == 1){
                throw new JeecgBootException("司机已经消费,余额不足不能回收!");
            }
        }
    }

    /**
     * 万金油回收查询余额
     * @param nucarfAppid
     * @param nucarfSecret
     * @param gasAmount
     * @param driverName
     */
    private void checkNucarfBackMoney(String nucarfAppid, String nucarfSecret, BigDecimal gasAmount, String driverName) {

        NucartResult<CUInfo> nucartResult = (NucartResult<CUInfo>) nucartUtils. getBackMoney(driverName, nucarfAppid, nucarfSecret) ;
        if(!nucartResult.isSuccess()) {
            throw new JeecgBootException("查询司机余额失败请重新查询!");
        }else{
            gasAmount = new BigDecimal(gasAmount.stripTrailingZeros().toPlainString());
            if(nucartResult.getResult() == null){
                throw new JeecgBootException("查询司机余额失败,请重新回收查询!");
            }
            Integer balance =  nucartResult.getResult().getBalance();
            if (balance != null ) {
                BigDecimal  balanceBig = new BigDecimal(balance.toString());
                if(gasAmount.compareTo(balanceBig) == 1){
                    throw new JeecgBootException("司机已经消费,余额不足不能回收!");
                }
            }
//            Integer waitMoney = nucartResult.getResult().getWait_money();
//            if (waitMoney != null ) {
//                BigDecimal  waitMoneyBig = new BigDecimal(waitMoney.toString());
//                if(gasAmount.compareTo(waitMoneyBig) == 1){
//                    throw new JeecgBootException("司机已经消费,待领取余额不足不能回收!");
//                }
//            }
        }
    }

    @Transactional
    public Result<?> useGas(String shippingId) {
        HyShippingNote hyShippingNote = hyShippingNoteService.getByIdForUpdate(shippingId);
        if(hyShippingNote == null){
            return Result.error("该运单不存在");
        }
        //  0 不使用 2  油卡
        if("0".equals(hyShippingNote.getIzUsedGas()) || "2".equals(hyShippingNote.getIzUsedGas()) ){
            return Result.error("不能分配油气");
        }


        HyDriver driver = hyDriverService.getById(hyShippingNote.getDriverId());
        if(driver == null){
            return Result.error("司机信息不存在");
        }
        HyVehicle vehicle = hyVehicleService.getById(hyShippingNote.getVehicleId());
        if(vehicle == null){
            return Result.error("车辆信息不存在");
        }
        BigDecimal gasRechargeAmount = hyShippingNote.getGasRechargeAmount();
        if(gasRechargeAmount == null){
            return Result.error("分配油气金额不正确");
        }
        // <=
        if(gasRechargeAmount.compareTo(BigDecimal.ZERO) ==-1){
            return Result.error("分配油气金额不正确");
        }

        String vehicleNumber = vehicle.getVehicleNumber();
        String driverName = driver.getDriverName();
        String idcard = driver.getIdcard();
        String telephone = driver.getTelephone();

        String sendAddress = hyShippingNote.getSendAddress();
        String receiveAddress = hyShippingNote.getReceiveAddress();
        String remark = "油气费,运单号:" + hyShippingNote.getShippingNoteNumber();

        HyShippingNoteGas gas = hyShippingNoteGasService.getByShippingId(hyShippingNote.getId());
        if (gas == null) {
            gas = new HyShippingNoteGas();
            gas.setShippingId(hyShippingNote.getId());
            gas.setShippingNoteNumber(hyShippingNote.getShippingNoteNumber());
            gas.setDriverId(hyShippingNote.getDriverId());
            gas.setDriverName(driverName);
            gas.setIzUsedGas(hyShippingNote.getIzUsedGas());
            gas.setGasRechargeAmount(gasRechargeAmount);
            gas.setVehicleNumber(vehicleNumber);
            gas.setVehicleEnergyType(vehicle.getVehicleEnergyType());
            gas.setGasStatus("2");// 直接设置给已充值状态
            hyShippingNoteGasService.save(gas);
        }else {
            if(!"9".equals(gas.getGasStatus())){
                return Result.error("不能充值!");
            }
        }
        if("1".equals(hyShippingNote.getIzUsedGas())){
            HyConfig gasConfig = this.checkConfig();
            String nucarfAppid = gasConfig.getGasAppid();
            String nucarfSecret = gasConfig.getGasSecret();

            gasRechargeAmount = gasRechargeAmount.multiply(new BigDecimal("100"));
            String money = gasRechargeAmount.toString();

            //充值
            NucartResult<CUInfo> r = (NucartResult<CUInfo>) nucartUtils.createUser(
                    driverName, telephone, idcard, vehicleNumber, money, nucarfAppid,
                    nucarfSecret,sendAddress,receiveAddress,remark,hyShippingNote.getShippingNoteNumber(),
                    vehicle.getVehicleEnergyType()

            );
            if(r.isSuccess()){
                BigDecimal gasAmount = gasRechargeAmount.divide(new BigDecimal("100"));
                String flowNum = StringUtils.isNotBlank(r.getResult().getFlowNumber()) ?  r.getResult().getFlowNumber() : StringUtils.EMPTY;
                gas.setGasAmount(gasAmount);
                gas.setGasFlowNumber(flowNum);
                gas.setRechargeTime(new Date());
                hyShippingNoteGasService.updateById(gas);
                return Result.OK("充值成功!");
            }else{
                gas.setGasStatus("9");
                gas.setGasRemark(r.getMessage());
                hyShippingNoteGasService.updateById(gas);
                return Result.error("充值失败！" + r.getMessage());
            }
        }

        if("3".equals(hyShippingNote.getIzUsedGas())) {
            HyConfig gasConfig = this.checkHgConfig();
            String hgGasAppid = gasConfig.getHgGasAppid() ;
            String hgGasSecret = gasConfig.getHgGasSecret() ;
            Result createUserResult  = hgFuelEnergyService
                    .createUser( driverName, telephone, idcard, vehicleNumber, hgGasAppid, hgGasSecret);
            if(!createUserResult.isSuccess()){
                return Result.error("充值失败！" + createUserResult.getMessage());
            }else {
                String money = gasRechargeAmount.toString() ;
                Result rechargeResult =  hgFuelEnergyService.userRecharge(
                        driverName, telephone, idcard, vehicleNumber, money, hgGasAppid,
                        hgGasSecret, sendAddress, receiveAddress, remark, hyShippingNote.getShippingNoteNumber(),
                        vehicle.getVehicleEnergyType()
                ); if (rechargeResult.isSuccess()) {
                    gas.setGasStatus("2");
                    gas.setGasAmount(gasRechargeAmount );
                    gas.setGasFlowNumber("");
                    gas.setRechargeTime(new Date());
                    hyShippingNoteGasService.updateById(gas);
                    return Result.OK("充值成功!");
                }else {
                    gas.setGasStatus("9");
                    gas.setGasRemark(rechargeResult.getMessage());
                    hyShippingNoteGasService.updateById(gas);
                    return Result.error("充值失败！" + rechargeResult.getMessage());
                }
            }
        }

        return Result.OK("充值失败!");
    }


    public  HyConfig  checkConfig(){
        HyConfig gasConfig = HyConfigUtils.getConfig();
        if (gasConfig == null) {
            throw new JeecgBootException("未找到万金油油气配置信息!");
        }
        if (!gasConfig.getGasIzUse()) {
            throw new JeecgBootException("万金油油气功能已关闭!");
        }
        String nucarfAppid = gasConfig.getGasAppid();
        String nucarfSecret = gasConfig.getGasSecret();
        if (StringUtils.isEmpty(nucarfAppid) || StringUtils.isEmpty(nucarfSecret)) {
            throw new JeecgBootException("万金油油气参数错误!");
        }
        return gasConfig;
    }

    public HyConfig  checkHgConfig(){
        HyConfig gasConfig = HyConfigUtils.getConfig();
        if(gasConfig == null){
            throw new JeecgBootException("未找到油气平台配置信息!");
        }
        if(!gasConfig.getHgGasIzUse()){
            throw new JeecgBootException("油气平台功能已关闭!");
        }
        String hgGasAppid = gasConfig.getHgGasAppid() ;
        String hgGasSecret = gasConfig.getHgGasSecret() ;

        if(StringUtils.isEmpty(hgGasAppid)|| StringUtils.isEmpty(hgGasSecret)){
            throw new JeecgBootException("油气平台参数错误!");
        }
        return gasConfig;
    }
}




